﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Littlebeer.MDM.MSO
{
    public class TableManager
    {
        string _Conn;

        public string Conn
        {
            get { return _Conn; }
            set { _Conn = value; }
        }
        public TableManager(string conn)
        {
            _Conn = conn;
        }
        public void AddColumn(DataTable dt, string columnName)
        {
            if (!CheckColumnExist(dt, columnName))
            {
                dt.Columns.Add(columnName);
            }
        }
        public void AddPrimaryKey(DataTable dt, string columnName)
        {
            if (!CheckColumnExist(dt, columnName))
            {
                DataColumn pk = new DataColumn(columnName);
                dt.Columns.Add(pk);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    dt.Rows[i][columnName] = i;
                }
                dt.PrimaryKey = new DataColumn[] { pk };
            }
            else
            {
                throw (new Exception(string.Format("自动添加的主键字段（{0}）重复！",columnName)));
            }
        }
        public void AddColumn(DataTable dt, string columnName, List<string> columns)
        {
            if (!CheckColumnExist(dt, columnName))
            {
                DataColumn col = new DataColumn(columnName);
                col.Expression ="["+ string.Join("]+[",columns)+"]";
                dt.Columns.Add(col);
            }
        }
        public Boolean CheckColumnExist(DataTable dt, string columnName)
        {
            Boolean result = false;
            foreach (DataColumn item in dt.Columns)
            {
                if (item.ColumnName.ToLower() == columnName.ToLower())
                {
                    return true;
                }
            }
            return result;
        }

        public string  GetIdendtityColumn(string entityName)
        {
            string result = "";
            string sql =string.Format( @"select top 1 c.name from SYS.all_columns c,sys.all_objects o
WHere c.object_id=o.object_id and o.name='{0}' and c.is_identity=1 ",entityName);
            using (SqlConnection cn = new SqlConnection(_Conn))
            {
                cn.Open();
                SqlCommand com = new SqlCommand(sql, cn);
                result = com.ExecuteScalar().ToString();
                cn.Close();
            }
            return result;
        }
    }
}
